﻿Public Class CtlSigortali2 : Inherits BaseControl

	Dim NoEvents As Boolean
	Public WithEvents Search As New TextBox
	Dim SNoLabel As New Label
	Public WithEvents SNo As New TextBox
	Dim WithEvents Results As New Grid
	Dim WithEvents Dropdown As New ToolStripDropDown

	Property Type As Integer
	Public Local As Boolean = False

	Overrides Sub Reset()
		Value = ""
	End Sub

	Overrides Property MinimumSize() As System.Drawing.Size
		Get
			Return New Size(360, ControlHeight)
		End Get
		Set(ByVal Value As System.Drawing.Size)
			MyBase.MinimumSize = Value
		End Set
	End Property

	Overrides Property MaximumSize() As System.Drawing.Size
		Get
			Return MinimumSize
		End Get
		Set(ByVal Value As System.Drawing.Size)
			MyBase.MaximumSize = Value
		End Set
	End Property

	Private Sub GenericChange(ByVal Sender As Object, ByVal EventType As GenericEventType, ByVal Param As String) Handles Search.GenericEvent, SNo.GenericEvent
		If NoEvents Then Exit Sub
		If EventType <> GenericEventType.Change Then Exit Sub
		Process.Tip.Destroy()
		RaiseChangeEvent()
		For Each Control As Object In Controls
			If TypeName(Control) = "Generic" Then
				If Not (Control Is Sender) Then Control.value = ""
			End If
		Next
		m_Value = ""
	End Sub

	ReadOnly Property Token As Token
		Get
			Return If(Local, Process.Local, Process.Remote)
		End Get
	End Property

	Dim m_Value As Object
	Property Value() As Object
		Get
			Return m_Value
		End Get
		Set(ByVal Value As Object)
			If IsNull(Trim(Value), "") = IsNull(Trim(m_Value), "") Then Return
			m_Value = Trim(Value)
			If m_Value = "" Then
				SNo.Value = ""
				Search.Value = ""
			Else
				If Type = 0 Then
					Dim Rs As Recordset = Sigortali.SnoAra(Token, m_Value)
					If Check(SNo, Rs.EOF, "Sigorta numarası bulunamadı.") Then Exit Property
					DisplayResults(Rs)
				Else
					Dim Rs As Recordset = Emeklilik.KimlikAra(Token, m_Value)
					If Check(Search, Rs.EOF, "Kimlik numarası bulunamadı.") Then Exit Property
					DisplayResults(Rs)
				End If
			End If
		End Set
	End Property

	Public Sub New()
		Size = MinimumSize
		DoubleBuffered = True
		Controls.Add(Search)
		Search.Location = New Point(0, 0)
		Search.Width = Width
		Search.DefaultText = "Kimlik, adı soyadı veya pasaport."
		Search.Casing = CharacterCasing.Upper
		Search.UseEnterAsTab = False
		Search.Focus()
		Controls.Add(SNo)
		Controls.Add(SNoLabel)
		SNoLabel.Text = "Sigorta no.:"
		SNoLabel.AutoSize = False
		SNoLabel.TextAlign = ContentAlignment.MiddleRight
		SNoLabel.ForeColor = SystemColors.GrayText
		SNoLabel.Size = New Size(70, Height - 2)
		SNo.Width = 60
		SNo.Location = New Point(Search.Right - SNo.Width, 0)
		SNo.UseEnterAsTab = True
		SNo.AllowOnlyNumeric = True
		'SNo.DefaultText = "Sigorta no."
		SNo.TextAlign = HorizontalAlignment.Center
		SNo.MaxLength = 9
		SNo.UseEnterAsTab = False
		SNo.BringToFront()
		SNoLabel.Location = New Point(SNo.Left - SNoLabel.Width, 0)
		SNoLabel.BringToFront()
		Dim Host As New ToolStripControlHost(Results)
		Dropdown.Items.Add(Host)
		Results.AddColumns("adisoyadi(Adı soyadı;l;100%),kimlikno(Kimlik no.;c;70),sno(Sigorta no.;c;70),dtar(Doğum tar.;c;70)")
		Results.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None
		Results.MultiSelect = False
		Results.StandardTab = True
		Dropdown.RenderMode = ToolStripRenderMode.System
		Dropdown.Padding = New Padding(0)
		Dropdown.Margin = New Padding(0)
		Host.AutoSize = False
		Host.Padding = New Padding(1)
		Host.Margin = New Padding(1)
		Host.BackColor = SystemColors.ButtonFace
	End Sub

	Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
		If keyData = Keys.Enter Or keyData = Keys.Tab Then
			If ActiveControl Is SNo Then
				Dim Result As String = AraSNo()
				If Result = "nd" Then Parent.SelectNextControl(Me, True, True, True, True)
				If Result = "f" Then Parent.SelectNextControl(Me, True, True, True, True)
			ElseIf ActiveControl Is Search Then
				Dim Result As String = AraDiger()
				If Result = "nd" Then SNo.Focus()
				If Result = "f" Then Parent.SelectNextControl(Me, True, True, True, True)
			End If
			Return True
		End If
		Return MyBase.ProcessCmdKey(msg, keyData)
	End Function

	Function Ara(control As String, value As String) As String
		If control = "search" Then
			Search.Value = value
			Search.IsDirty = True
			Return AraDiger()
		ElseIf control = "sno" Then
			SNo.Value = value
			SNo.IsDirty = True
			Return AraSNo()
		End If
		Return ""
	End Function

	Function AraSNo() As String
		If Not SNo.IsDirty Then Return "nd"
		Dim Rs As Recordset = Sigortali.SnoAra(Token, SNo.Value)
		If Check(SNo, Rs.EOF, "Sigorta numarası bulunamadı.") Then SNo.Focus() : Return ""
		DisplayResults(Rs)
		Return "f"
	End Function

	Function AraDiger() As String
		If Not Search.IsDirty Then Return "nd"
		Search.IsDirty = False
		If IsNumeric(Search.Text) Then Return AraKimlik()
		If ispassport(Search.Text) Then Return AraPasaport()
		Return AraAdSoyad()
	End Function

	Function IsPassport(t As String) As Boolean
		Dim Counts(1) As Integer
		For Each c In t
			Counts(If(IsNumeric(c), 0, 1)) += 1
		Next
		If Counts(0) > 1 And Counts(1) > 0 Then Return True
	End Function

	Function AraKimlik() As String
		Dim Rs As Recordset = Nothing
		Dim Kimlik = Search.Text
		If Kimlik.Length < 6 Then Kimlik = Kimlik.PadLeft(6, "0")
		If Type = 0 Then
			Rs = Sigortali.KimlikAra(Token, Kimlik)
			Dim Rss As Recordset = Rs.GroupBy("sno,count(*)")
			If Check(Search, Rss.EOF, "Kimlik numarası bulunamadı.") Then Return "nf"
			If Rss.Count = 1 Then
				Rs = Sigortali.SnoAra(Token, Rss("sno"))
				DisplayResults(Rs)
				Return "f"
			Else
				Warning("Dikkat! Bu kimliğe sahip birden fazla sigortalı kaydı vardır. Hatalı kayıtların düzeltilmesi gerekmektedir.")
				Dim Dialog As New SigortaliHizliArama()
				Dialog.AddArgument("type", Type)
				Dialog.AddArgument("rs", Rs)
				Dialog.Run(Process.Window)
				Dim Sonuc As String = Dialog.Result
				If Sonuc = "" Then SNo.Focus() : Return "nf"
				Rs = Sigortali.SnoAra(Token, Sonuc)
				DisplayResults(Rs)
				Return "f"
			End If
		ElseIf Type = 1 Then
			Rs = Emeklilik.KimlikAra(Token, Kimlik)
			If Check(Search, Rs.EOF, "Kimlik numarası bulunamadı.") Then Return "nf"
		End If
		DisplayResults(Rs)
		Return "f"
	End Function

	Function AraPasaport() As String
		Dim Rs As Recordset = Nothing
		Dim Pasaport = Search.Text
		Rs = Sigortali.PasaportAra(Token, Pasaport)
		Dim Rss As Recordset = Rs.GroupBy("sno,count(*)")
		If Check(Search, Rss.EOF, "Pasaport numarası bulunamadı.") Then Return "nf"
		If Rss.Count = 1 Then
			Rs = Sigortali.SnoAra(Token, Rss("sno"))
			DisplayResults(Rs)
			Return "f"
		Else
			Warning("Dikkat! Bu pasaporta sahip birden fazla sigortalı kaydı vardır. Hatalı kayıtların düzeltilmesi gerekmektedir.")
			Dim Dialog As New SigortaliHizliArama()
			Dialog.AddArgument("type", Type)
			Dialog.AddArgument("rs", Rs)
			Dialog.Run(Process.Window)
			Dim Sonuc As String = Dialog.Result
			If Sonuc = "" Then SNo.Focus() : Return "nf"
			Rs = Sigortali.SnoAra(Token, Sonuc)
			DisplayResults(Rs)
			Return "f"
		End If
		DisplayResults(Rs)
		Return "f"
	End Function

	Function AraAdSoyad() As String
		Dim Rs As Recordset = Nothing
		Dim Sonuc As String
		If Len(Search.Text) < 2 Then Return "nf"
		Select Case Type
			Case 0 : Rs = Sigortali.AdSoyadAra(Token, Trim(Search.Text))
			Case 1 : Rs = Emeklilik.AdSoyadAra(Token, Trim(Search.Text))
		End Select
		If Check(Search, Rs.EOF, "Bu isimde biri bulunamadı.") Then Return "nf"
		If Rs.Rows.Count = 1 Then
			Sonuc = Rs(Choose(Type + 1, "sno", "kimlik"))
		Else
			If Type = 0 Then
				'Rs = Sigortali.SnoAraListe(Token, Rs.ToString("sno", "", ","))
			Else
				Rs = Emeklilik.KimlikAraListe(Token, "'" & Rs.ToString("kimlik", "", "','") & "'")
			End If
			Results.Rows.Clear()
			Do Until Rs.EOF
				Results.Rows.Add(Trim(Rs("adi")) & " " & Trim(Rs("soyadi")), Rs("kimlik"), Rs("sno"), DMY(Rs("dtar")))
				Rs.MoveNext()
			Loop
			Results.MinimumSize = New Size(Width + 4, Math.Min(10, Results.Rows.Count) * Results.Rows(0).Height + Results.ColumnHeadersHeight)
			Results.MaximumSize = Results.MinimumSize
			Results.Font = New Font(Font.Name, Font.Size - 2)
			Dropdown.Show(Me, New Point(-3, Height + 3))
			Results.Focus()
			Return "nf"
		End If
		Select Case Type
			Case 0 : Rs = Sigortali.SnoAra(Token, Sonuc)
			Case 1 : Rs = Emeklilik.KimlikAra(Token, Sonuc)
		End Select
		DisplayResults(Rs)
		Return "f"
	End Function

	Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
		e.Graphics.FillRectangle(New SolidBrush(Color.Red), ClientRectangle)
	End Sub

	Public Overridable ReadOnly Property IsEmpty() As Boolean
		Get
			Return Value = ""
		End Get
	End Property

	Private Sub SNo_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SNo.Validating
		If Not SNo.IsDirty Then Return
		Dim Result As String = AraSNo()
		If Result = "f" Then Return
		e.Cancel = True
	End Sub

	Private Sub DisplayResults(ByVal Rs As Recordset)
		NoEvents = True
		If Type = "0" Then
			m_Value = Trim(Rs("sno"))
		Else
			m_Value = Trim(Rs("kimlik"))
		End If
		SNo.Text = Trim(Rs("sno"))
		'Dim Rsb As Recordset = Sigortali.BeyazKimlik.SNoAra(Token, Rs("sno"))
		'If Not Rsb.EOF Then
		'	beyazkimlik = Rsb("beyazkno")
		'	beyazkimliktar = DMY(Rsb("kimliktar"))
		'End If
		Search.Text = Trim(Rs("adi")) & " " & Trim(Rs("soyadi")) & " - " & Trim(Rs("kimlik"))
		Search.IsDirty = False
		Invalidate()
		NoEvents = False
	End Sub

	Private Sub Search_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Search.Validating
		If Not Search.IsDirty Then Return
		Dim Result As String = AraDiger()
		If Result = "f" Then Return
		e.Cancel = True
	End Sub

	Private Sub Results_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Results.KeyDown
		If e.KeyCode = Keys.Enter Then
			e.Handled = True
			SelectResult()
		ElseIf e.KeyCode = Keys.Tab And e.Shift Then
			e.Handled = True
			Search.Focus()
		End If
	End Sub

	Private Sub Results_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Results.MouseClick
		SelectResult()
	End Sub

	Sub SelectResult()
		Dropdown.Hide()
		Dim Rs As Recordset = Sigortali.SnoAra(Token, Results.SelectedRows(0).Cells(2).Value)
		DisplayResults(Rs)
		Search.SelectAll()
	End Sub

	Private Sub Results_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Results.MouseMove
		Dim Info As DataGridView.HitTestInfo = Results.HitTest(e.X, e.Y)
		If Info.RowIndex >= 0 Then
			Results.Rows(Info.RowIndex).Selected = True
		End If
	End Sub

	Public Overrides Function Errors() As String
		If IsRequired AndAlso IsEmpty Then Return Caption & " alanı boş olamaz."
		Return ""
	End Function

End Class

